package com.xunyin.utils;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ConnectTimeoutException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class TuyaHttpClientUtil {
    private static int socketTimeout = 10000;
    private static int connectTimeout = 30000;
    private static RequestConfig requestConfig;
    private static CloseableHttpClient httpClient;

    public TuyaHttpClientUtil() {
    }

    public static String doGet(String url, Map<String, String> param) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;

        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                Iterator var6 = param.keySet().iterator();

                while (var6.hasNext()) {
                    String key = (String) var6.next();
                    builder.addParameter(key, (String) param.get(key));
                }
            }

            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            if (param != null) {
                Iterator var6 = param.keySet().iterator();

                while (var6.hasNext()) {
                    String key = (String) var6.next();
                    httpGet.addHeader(key, (String) param.get(key));
                }
            }
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception var16) {
            var16.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }

                httpclient.close();
            } catch (IOException var15) {
                var15.printStackTrace();
            }

        }

        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, (Map) null);
    }

    public static String doPost(String url, Map<String, String> param) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            HttpPost httpPost = new HttpPost(url);
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList();
                Iterator var7 = param.keySet().iterator();

                while (var7.hasNext()) {
                    String key = (String) var7.next();
                    paramList.add(new BasicNameValuePair(key, (String) param.get(key)));
                }

                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
            }

            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception var17) {
            var17.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException var16) {
                var16.printStackTrace();
            }

        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, (Map) null);
    }

    public static String doPostJson(String url, String json, Map headerParam) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            if (headerParam != null) {
                Iterator var7 = headerParam.keySet().iterator();

                while (var7.hasNext()) {
                    String key = (String) var7.next();
                    httpPost.addHeader(key, (String) headerParam.get(key));
                }
            }

            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception var15) {
            var15.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException var14) {
                var14.printStackTrace();
            }

        }

        return resultString;
    }

    public static String doPostXml(String url, String xml) {
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;

        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8");
            client = HttpClients.createDefault();
            StringEntity entityParams = new StringEntity(xml, "utf-8");
            httpPost.setEntity(entityParams);
            client = HttpClients.createDefault();
            resp = client.execute(httpPost);
            String resultMsg = EntityUtils.toString(resp.getEntity(), "utf-8");
            String var7 = resultMsg;
            return var7;
        } catch (Exception var17) {
            var17.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    client.close();
                }

                if (resp != null) {
                    resp.close();
                }
            } catch (IOException var16) {
                var16.printStackTrace();
            }

        }

        return null;
    }

    public static String doPostXmlCert(String url, String xmlObj, String mchId, String certPath) {
        try {
            initCert(mchId, certPath);
        } catch (Exception var18) {
            var18.printStackTrace();
        }

        String result = null;
        HttpPost httpPost = new HttpPost(url);
        StringEntity postEntity = new StringEntity(xmlObj, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
        httpPost.setConfig(requestConfig);

        try {
            CloseableHttpResponse response = null;

            try {
                response = httpClient.execute(httpPost);
            } catch (IOException var16) {
                var16.printStackTrace();
            }

            HttpEntity entity = response.getEntity();

            try {
                result = EntityUtils.toString(entity, "UTF-8");
            } catch (IOException var15) {
                var15.printStackTrace();
            }
        } finally {
            httpPost.abort();
        }

        return result;
    }

    private static void initCert(String mchId, String certPath) throws Exception {
        String key = mchId;
        Resource resource = new ClassPathResource(certPath);
        File file = resource.getFile();
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(file);

        try {
            keyStore.load(instream, key.toCharArray());
        } finally {
            instream.close();
        }

        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchId.toCharArray()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, (String[]) null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

    /**
     * 图片流
     *
     * @param url
     * @param map
     * @return
     */
    public static byte[] doImgPost(String url, Map<String, Object> map) {
        byte[] result = null;
        //使用HTTPPost方法访问获取二维码链接url
        HttpPost httpPost = new HttpPost(url);
        //创建http连接客户端
        CloseableHttpClient client = HttpClients.createDefault();
        //设置头响应类型
        httpPost.addHeader("Content-Type", "application/json");
        try {
            // 设置请求的参数
            JSONObject postData = new JSONObject();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                postData.put(entry.getKey(), entry.getValue());
            }
            httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8"));
            //返回的post请求结果
            HttpResponse response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toByteArray(entity);
        } catch (ConnectionPoolTimeoutException e) {
        } catch (ConnectTimeoutException e) {
        } catch (SocketTimeoutException e) {
        } catch (Exception e) {
        } finally {
            httpPost.releaseConnection();
        }
        //最后转成2进制图片流
        return result;
    }
}
